package com.imooc.infra.repository.jdbc;

import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.stereotype.Component;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

/**
 * @Author Tim
 * @Description:
 * @Version 1.0
 */
@Component
public class JdbcDataSourceTractionManager {

    private final DataSourceTransactionManager dataSourceTransactionManager;
    public JdbcDataSourceTractionManager(DataSourceTransactionManager dataSourceTransactionManager) {
        this.dataSourceTransactionManager = dataSourceTransactionManager;
    }

    /**
     * 开启事务
     * @return
     */
    public TransactionStatus begin() {
        return doBegin(TransactionDefinition.PROPAGATION_REQUIRED);
    }

    /**
     * 提交事务
     * @param status
     */
    public void commit(TransactionStatus status) {
        dataSourceTransactionManager.commit(status);
    }

    /**
     * 回滚事务
     * @param status
     */
    public void rollback(TransactionStatus status) {
        dataSourceTransactionManager.rollback(status);
    }

    private TransactionStatus doBegin(int transactionDefinition) {
        DefaultTransactionDefinition defaultTransactionDefinition = new DefaultTransactionDefinition();
        defaultTransactionDefinition.setPropagationBehavior(transactionDefinition);
        return dataSourceTransactionManager.getTransaction(defaultTransactionDefinition);
    }
}
